package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.ISearchService;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ISearchServiceImpl implements ISearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    //自动补全功能
    @Override
    public List<String> getCompletion(String prefix) throws IOException {
        //1、准备request
        SearchRequest request = new SearchRequest("item");
        //2、准备dsl
        request.source().suggest(
                new SuggestBuilder().addSuggestion(
                        "my_suggestion",
                        SuggestBuilders.completionSuggestion("suggestion")
                                .prefix(prefix)
                                .skipDuplicates(true)
                                .size(10)
                )
        );
        //3、发出请求
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        //4、结果解析
        Suggest suggest = response.getSuggest();
        //4.1根据补全查询结果，获取补全结果
        CompletionSuggestion suggestions = suggest.getSuggestion("my_suggestion");
        //4.2获取option
        List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
        //4.3遍历options
        ArrayList<String> list = new ArrayList<>(options.size());
        for (CompletionSuggestion.Entry.Option option : options) {
            String text = option.getText().toString();
            list.add(text);
        }
        return list;
    }

    //基础查询功能
    @Override
    public PageDTO<ItemDoc> select(RequestParams requestParams) throws IOException {
        //准备request
        SearchRequest request = new SearchRequest("item");
        //准备dsl
        buildBasicQuery(requestParams, request);

        //分页
        Integer page = requestParams.getPage();
        Integer size = requestParams.getSize();
        request.source().from((page - 1) * size).size(size);

        //排序
        String sortBy = requestParams.getSortBy();
        if ("sold".equals(sortBy)) {
            request.source().sort(sortBy, SortOrder.DESC);
        } else if ("price".equals(sortBy)) {
            request.source().sort(sortBy, SortOrder.ASC);
        }
        //高亮显示
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

        //发出请求
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        /*return*/
        return handleResponse(response);
    }

    //查询过滤项
    @Override
    public Map<String, List<String>> getFilters(RequestParams requestParams) throws IOException {
        //准备request
        SearchRequest request = new SearchRequest("item");
        //准备dsl
        //query
        buildBasicQuery(requestParams,request);
        //设置size
        request.source().size(0);
        //聚合
        buildAggregation(request);
        //发出请求
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //解析结果
        Map<String,List<String>> result = new HashMap<>();
        Aggregations aggregations = response.getAggregations();
        //根据名称,获取结果
        List<String> categoryList = getAggByName(aggregations,"categoryAgg");
        result.put("category",categoryList);

        List<String> brandList = getAggByName(aggregations,"brandAgg");
        result.put("brand",brandList);

      /*  List<String> priceList = getAggByName(aggregations,"priceAgg");
        result.put("价格",priceList);*/
        return result;
    }

    @Autowired
    private ItemClient itemClient;
    //上架
    @Override
    public void upItem(Long id) throws IOException {
        //根据id查询商品数据（feign）
        Item item = itemClient.selectById(id);
        //转换为文档类型
        ItemDoc itemDoc = new ItemDoc(item);
        //准备request
        IndexRequest request = new IndexRequest("item").id(item.getId().toString());
        //准备json
        request.source(JSON.toJSONString(itemDoc),XContentType.JSON);
        //发送请求
        restHighLevelClient.index(request,RequestOptions.DEFAULT);

    }

    //下架
    @Override
    public void downItem(Long id) throws IOException {
        //准备request
        DeleteRequest request = new DeleteRequest("item", id.toString());
        //发送请求
        restHighLevelClient.delete(request,RequestOptions.DEFAULT);

    }

    //根据名称聚合
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        Terms terms = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        //遍历
        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            list.add(key);
        }

        return list;
    }

    //聚合
    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(
                AggregationBuilders.terms("categoryAgg").field("category").size(100)
        );
        request.source().aggregation(
                AggregationBuilders.terms("brandAgg").field("brand").size(100)
        );

    }

    //query
    private void buildBasicQuery(RequestParams requestParams, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = requestParams.getKey();
        if (key == null || "".equals(key)){
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }
        //分类条件
        if(requestParams.getCategory() != null && !requestParams.getCategory().equals("")){
            boolQuery.filter(QueryBuilders.termQuery("category",requestParams.getCategory()));
        }

        //品牌条件
        if(requestParams.getBrand() != null && !"".equals(requestParams.getBrand())){
            boolQuery.filter(QueryBuilders.termQuery("brand",requestParams.getBrand()));
        }
        //价格条件
        if(requestParams.getMinPrice() != null && requestParams.getMaxPrice() != null){
            boolQuery.filter(QueryBuilders
                                .rangeQuery("price")
                                .gte(requestParams.getMinPrice().longValue()*100)
                                .lte(requestParams.getMaxPrice().longValue()*100)
            );
        }


        //权重比
        FunctionScoreQueryBuilder queryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(100)
                        )
                }
        );

        request.source().query(queryBuilder);
    }


    //结果解析方法
    private PageDTO<ItemDoc> handleResponse(SearchResponse response) throws JsonProcessingException {
        //解析响应
        SearchHits searchHits = response.getHits();
        //获取总条数
        long total = searchHits.getTotalHits().value;
        //文档数组
        SearchHit[] hits1 = searchHits.getHits();
        List<ItemDoc> itemDocs = new ArrayList<>();
        for (SearchHit hit : hits1) {
            String json = hit.getSourceAsString();
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if(highlightFields != null && highlightFields.size()>0){
                HighlightField highlightField = highlightFields.get("name");
                String value = highlightField.getFragments()[0].string();
                itemDoc.setName(value);
            }
            itemDocs.add(itemDoc);
        }
        return new PageDTO<>(total,itemDocs);
    }
}